package com.lizhongbao.cloud.gateway.filter;

import io.github.bucket4j.Bandwidth;
import io.github.bucket4j.Bucket;
import io.github.bucket4j.Bucket4j;
import io.github.bucket4j.Refill;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName LimitFilter
 * @Description 过滤器，用于限流
 * @Author lizhongbao
 * @Date 2019/12/6 11:11
 * @Version 1.0
 **/
public class LimitFilter implements GatewayFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(LimitFilter.class);

    /**
     * 每秒处理请求量
     */
    private int capacity;
    /**
     * 令牌桶容积
     */
    private int refillTokens;
    private Duration refillDuration;

    public LimitFilter(int capacity, int refillTokens, Duration refillDuration) {
        this.capacity = capacity;
        this.refillTokens = refillTokens;
        this.refillDuration = refillDuration;
    }

    private static final Map<String, Bucket> CACHE = new ConcurrentHashMap<>();

    private Bucket createNewBucket() {
        Refill refill = Refill.greedy(refillTokens, refillDuration);
        Bandwidth limit = Bandwidth.classic(capacity, refill);
        return Bucket4j.builder().addLimit(limit).build();
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 根据ip限流
        String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
        Bucket bucket = CACHE.computeIfAbsent(ip, k -> createNewBucket());

        // 正常访问
        logger.info("IP: "+ip+", available tokens :"+bucket.getAvailableTokens());
        if (bucket.tryConsume(1L)) {
            return chain.filter(exchange);
        }

        // 访问次数过多
        logger.info("IP: "+ip+", available tokens :"+bucket.getAvailableTokens()+" too many requests");
        // 返回json
        return fallBack(exchange);

//        // 直接返回异常
//        exchange.getResponse().setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
//        return exchange.getResponse().setComplete();

//        // 重定向
//        return fallBack("/fallback", exchange);

    }

    /**
     * 重定向
     * @param url
     * @param exchange
     * @return
     */
    private Mono<Void> fallBack(String url,ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.SEE_OTHER);
        response.getHeaders().set("Location", url);
        return exchange.getResponse().setComplete();
    }

    /**
     * 失败返回message提示用户
     * @param exchange
     * @return
     */
    private Mono<Void> fallBack(ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        String msg = "{\"code\":" + HttpStatus.TOO_MANY_REQUESTS + ",\"message\": \"" + HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase() + "\"}";
        byte[] bits = msg.getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        response.setStatusCode(HttpStatus.TOO_MANY_REQUESTS);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
